package com.lingyun.framework.security;

import com.lingyun.common.utils.StringUtils;
import com.lingyun.common.utils.jwt.JwtUtils;
import com.lingyun.common.vo.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 *
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        LoginUser loginUser = jwtUtils.getLoginUser(httpServletRequest);
        System.out.println("request-url======================》" + httpServletRequest.getRequestURI());
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(getAuthentication())) {
            jwtUtils.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, loginUser.getPassword(), loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    /**
     * 获取Authentication
     *
     * @return 当前登录用户的权限信息
     */
    public static Authentication getAuthentication() {
        // 获取当前登录用户的权限信息
        return SecurityContextHolder.getContext().getAuthentication();
    }


}
